<template>
	<u--form labelPosition="left" :model="umodel" ref="uForm" class="form" labelWidth="200rpx"
	         errorType="toast">
			     <view class="upload-scan">
			         <scan-bar id="scanInput" ref="storageUnitScanBarRef" placeholder="扫描工作中心" @code-scanned="getStorageUnitByCode" :key="datekey"></scan-bar>
			     </view>
			 <u-form-item label="工作中心" prop="workShopCodeName"  >
			   <u--input v-model="umodel.workShopCodeName" disabled inputAlign="right" clearable
			             border="none" placeholder="工作中心"></u--input>
			 </u-form-item>
	           
	</u--form>
	<view class="baseForm">
		
		<!-- tab-bar切换 -->
		<view class="tab-bar">
			<u-tabs
				:current="activeTab"
				:list="tabList"
				:scrollable="false"
				:activeStyle="{
					color: '#000',
					fontWeight: 'bold',
					transform: 'scale(1.04)'
				}"
				lineWidth="50px"
				lineHeight="2px"
				lineColor="#007aff"
				@change="changeTab"
			></u-tabs>
		</view>

		<!-- 待完成信息 -->
		<view v-if="activeTab === 0" class="activeHeight">
			<!-- 列表 -->
			<u-list @scrolltolower="scrolltolower" class="list" v-if="total" :height="listHeight" lowerThreshold="100px">
				<u-list-item v-for="(item, index) in tableList" :key="item.id">
					<view class="card">
						<view class="right">
							<view class="des">生产批次：{{ item?.planBatch || '' }}</view>
							<view class="des">批次数量：{{ item?.planBatchNum || 0 }}</view>
							<view class="des">总成物料：{{ item?.materialCode || '' }}-{{ item?.materialName || '' }}</view>
							<view class="des">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;图号：{{ item?.figureNumber || '' }}</view>
							<!-- <view class="des" style="height: auto;" v-for="(i, index1) in item?.productionMaterialCodes" :key="index1">
								<view>半成品物料：
								{{ i || '' }}-{{ item.productionMaterialNames[0] || '' }} &nbsp;&nbsp;</view>
								<view>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;图号：
								{{ item.productionMaterialFigureNumbers[index1] || '' }}</view>
							</view> -->
							<view class="des" style="height: auto;" v-for="(i, index1) in item?.componentMaterialCodes" :key="index1">
								<view>组件物料：
								{{ i || '' }}-{{ item.componentMaterialNames[index1] || '' }} &nbsp;&nbsp;</view>
								<view>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;图号：
								{{ item.componentMaterialFigureNumbers[index1] || '' }}</view>
							</view>
							<view class="title">
								{{ item?.workOrderCode || '' }}
								<!-- {{ item?.plannedBatchId || '' }} -->
							</view>
						</view>
						<view class="left">
							<view class="des">计划月数：{{item?.planYear || ''}}-{{ item?.planMonth || '' }}</view>
							<view class="des">已产数量：{{ item?.planFinishQuantity || 0 }}</view>
							<view class="des" v-if="item?.isCasual == 1">是否临时：是</view>
							<view class="des" v-else></view>
							<view class="des"></view>
							<view class="des" style="height: auto;" v-for="(i, index1) in item?.ids" :key="index1">
								<view>&nbsp;</view>
								<view>&nbsp;</view>
							</view>
							<view class="title">
								<button v-show="item?.isSelect" class="uni-btn" size="mini" type="primary">已选择</button>
								<button v-show="!item?.isSelect" class="uni-btn" size="mini" plain type="primary" @click="selectWorkOrder(item, index)">选 择</button>
							</view>
						</view>
					</view>
				</u-list-item>
			</u-list>
			<!-- 空数据 -->
			<view v-else>
				<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
			</view>
		</view>

		<!-- 已完成信息 -->
		<view v-else class="activeHeight">
			<!-- 列表 -->
			<u-list @scrolltolower="finishScrolltolower" class="list" v-if="finishTotal" :height="listHeight" lowerThreshold="100px">
				<u-list-item v-for="(item, index) in finishTableList" :key="item.id">
					<view class="card">
						<view class="right">
							<view class="des">生产批次：{{ item?.planBatch || '' }}</view>
							<view class="des">批次数量：{{ item?.planBatchNum || 0 }}</view>
							<view class="des">总成物料：{{ item?.materialCode || '' }}-{{ item?.materialName || '' }}</view>
							<view class="des">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;图号：{{ item?.figureNumber || '' }}</view>
							<!--<view class="des" style="height: auto;" v-for="(i, index1) in item?.productionMaterialCodes" :key="index1">
								<view>半成品物料：
								{{ i || '' }}-{{ item.productionMaterialNames[0] || '' }} &nbsp;&nbsp;</view>
								<view>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;图号：
								{{ item.productionMaterialFigureNumbers[index1] || '' }}</view>
							</view> -->
							<view class="des" style="height: auto;" v-for="(i, index1) in item?.componentMaterialCodes" :key="index1">
								<view>组件物料：
								{{ i || '' }}-{{ item.componentMaterialNames[index1] || '' }} &nbsp;&nbsp;</view>
								<view>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;图号：
								{{ item.componentMaterialFigureNumbers[index1] || '' }}</view>
							</view>
							<view class="title">
								{{ item?.workOrderCode || '' }}
								<!-- {{ item?.plannedBatchId || '' }} -->
							</view>
						</view>
						<view class="left">
							<view class="des">计划月数：{{item?.planYear || ''}}-{{ item?.planMonth || '' }}</view>
							<view class="des">已产数量：{{ item?.planFinishQuantity || 0 }}</view>
							<view class="des" v-if="item?.isCasual == 1">是否临时：是</view>
							<view class="des" v-else></view>
							<view class="des"></view>
							<view class="des" style="height: auto;" v-for="(i, index1) in item?.ids" :key="index1">
								<view>&nbsp;</view>
								<view>&nbsp;</view>
							</view>
							<view class="title">
								<button class="uni-btn" size="mini" plain type="success">已完成</button>
							</view>
						</view>
					</view>
				</u-list-item>
			</u-list>
			<!-- 空数据 -->
			<view v-else>
				<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
			</view>
		</view>

		<u-modal :show="showImport" ref="uModal" :content="``" confirmText="确认" showCancelButton @cancel="cancelImport"
			@confirm="confirmImport">
			<view slot="content">
				是否选择当前生产批次的加工单！
				<view style="font-size: 20px; font-weight: bold;">
					批次： {{selectOrder.planBatch}}
				</view>
			</view>
		</u-modal>
	</view>
</template>

<script lang="ts" setup>
import { ref,reactive, computed, toRaw } from 'vue';
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import ScanBar from '@/components/scan-bar/index.vue';
import { http } from '@/utils/http';
import { PageResult, TabInfo } from '@/types/type';
import { useUserStore } from '@/stores/useUserStore';
import { useProduceStore } from '@/stores/useProduceStore';
// 重置表单信息 & 光标自动blur
const storageUnitScanBarRef = ref();
const datekey = ref(new Date());
// 校验提交
const uForm = ref();
const posting = ref(false);
// 表单数据定义
const umodel = reactive({
	workShopCode: '',
	workShopId: '',
    workShopName: '',
	workShopCodeName: '',
});
// 登录工作组信息
const loginWorkInfo = computed(() => JSON.parse(useUserStore().loginWorkInfo));
// 加工单信息
const workOrderList = computed(() => JSON.parse(useProduceStore().workOrderList));

const activeTab = ref(0);
const tabList = [{ name: '待完成' }, { name: '已完成' }];
function changeTab(val: TabInfo) {
	activeTab.value = val.index;
	if (val.index === 0 && !tableList.value.length&&loginWorkInfo.value.workCenterId) {
		current.value = 0;
		tableList.value = [];
		loadmore();
	} else if (val.index === 1) {
		finishCurrent.value = 0
		finishTableList.value=[];
		finishLoadmore();
	}
}
const size = ref("12px")
// 待完成数据
const tableList = ref([]);
const current = ref(0);
const totalPage = ref(0);
const total = ref(0);

// 已完成数据
const finishTableList = ref([]);
const finishCurrent = ref(0);
const finishTotalPage = ref(0);
const finishTotal = ref(0);

//列表高度
const listHeight = ref('');
async function getStorageUnitByCode(result: any) {
	if (result) {
  umodel.workShopCode = result;
  const data = await http({
    url: '/mes/mesworkshop/getByCode',
    method: 'POST',
	data: { workshopCode: umodel.workShopCode },
  });
  if(data.code != 200){
	  uni.$u.toast(data.massage);
	  return
  }
  umodel.workShopId=data.data.id
  umodel.workShopCode=data.data.workshopCode
  umodel.workShopName=data.data.workshopName
  umodel.workShopCodeName=umodel.workShopCode+'-'+umodel.workShopName
  loginWorkInfo.value.workCenterId=umodel.workShopId
  loginWorkInfo.value.workCenterCode=umodel.workShopCode
  loginWorkInfo.value.workCenterName=umodel.workShopName
  loginWorkInfo.value.crewId=data.data.crewId
  loginWorkInfo.value.crewName=data.data.crewName
  console.log(loginWorkInfo.value)
  useUserStore().setloginWorkInfo(loginWorkInfo.value);
  storageUnitScanBarRef.value.reset();
  // 清空加工单数据
  useProduceStore().setWorkOrderList([])
  uni.setStorageSync("workOrderList", '[]')
  current.value = 0;
  tableList.value = [];
  finishCurrent.value = 0
  finishTableList.value=[];
  loadmore()
  finishLoadmore()
  }
  else{
	  umodel.workShopCode = '';
  }
}
// 已完成列表获取
async function finishLoadmore(type?: string) {
	try {
		finishCurrent.value += 1;
		const result: PageResult<any> = await http({
			method: 'POST',
			url: '/mes/mesmemberloginrecord/getWorkFormList',
			data: {
				current: finishCurrent.value,
				size: 20,
				data: {
					workCenterId: loginWorkInfo.value.workCenterId,
					orderStates: 2
				}
			}
		});
		const list = result.data;
		console.log("finishTableList.value",finishTableList.value)
		for (let i = 0; i < list.length; i++) {
			finishTableList.value.push(list[i]);
		}
		console.log("finishTableList.value",finishTableList.value)
		finishTotalPage.value = result.page;
		finishTotal.value = result.total;
		type === 'refresh' && uni.stopPullDownRefresh();
	} catch (e) {
		console.log(e);
	}
}

onShow(() => {
	// #ifdef H5
	listHeight.value = 'calc(100vh - 88px)';
	// #endif

	// #ifdef APP-PLUS
	listHeight.value = 'calc(100vh - 44px)';
	// #endif
	current.value = 0;
	tableList.value = [];
	console.log("111",loginWorkInfo.value.workCenterId)
	if(loginWorkInfo.value.workCenterId)
	{
	loadmore();
	umodel.workShopName=loginWorkInfo.value.workCenterName
	umodel.workShopCodeName=loginWorkInfo.value.workCenterCode+'-'+loginWorkInfo.value.workCenterName
	}
});

onPullDownRefresh(() => {
	current.value = 0;
	tableList.value = [];
	loadmore('refresh');
	finishCurrent.value = 0;
	finishTableList.value=[];
	finishLoadmore('refresh');
});

async function loadmore(type?: string) {
	try {
		current.value += 1;
		const result: PageResult<any> = await http({
			method: 'POST',
			url: '/mes/mesmemberloginrecord/getWorkFormList',
			data: {
				current: current.value,
				size: 20,
				data: {
					workCenterId: loginWorkInfo.value.workCenterId,
					orderStates: 1
				}
			}
		});
		const list = result.data;
		const selectId = workOrderList.value != [] ? workOrderList.value[0]?.id : '';
		for (let i = 0; i < list.length; i++) {
			tableList.value.push({ ...list[i], isSelect: selectId == list[i]?.id ? true : false });
		}
		totalPage.value = result.page;
		total.value = result.total;
		type === 'refresh' && uni.stopPullDownRefresh();
	} catch (e) {
		console.log(e);
	}
}
const scrolltolower = () => {
	totalPage.value > current.value && loadmore();
};

const finishScrolltolower = () => {
	finishTotalPage.value > finishCurrent.value && finishLoadmore();
};

// 选择订单
const selectOrder = ref({});
const selectIndex = ref();
const showImport = ref(false);
function selectWorkOrder(row, index) {
	showImport.value = true;
	selectOrder.value = row;
	selectIndex.value = index;
}

// 取消选择订单
function cancelImport() {
	showImport.value = false;
	selectOrder.value = {};
	selectIndex.value = null;
}

function addWorkOrder() {
	return new Promise(async (resolve, reject) => {
		const res = await http({
			method: 'POST',
			url: '/mes/mesmemberloginrecord/selectWorkingForm',
			data: {
				workCenterId: loginWorkInfo.value.workCenterId,
				id: selectOrder.value.id
			}
		});
		resolve(res);
	});
}
// 追加加工单
async function confirmImport() {
	showImport.value = false;
	await addWorkOrder();
	useProduceStore().setWorkOrderList(toRaw(selectOrder.value));
	// 清空所有被选择状态
	for (let i = 0; i < tableList.value.length; i++) {
		tableList.value[i] = {
			...tableList.value[i],
			isSelect: false
		};
	}
	// 更新给当前加工单状态
	tableList.value[selectIndex.value] = {
		...tableList.value[selectIndex.value],
		isSelect: true
	};
	uni.showToast({
		title: '选择成功'
	});
}
</script>

<style lang="scss" scoped>
	.upload-scan {
			padding: 10px 40rpx 10px 40rpx;
		}
		.form {
				padding: $uni-page-padding;
			}
		
		.u-form {
		  margin-top: 10px;
		
		  .scan-bar {
		    display: flex;
		    flex: 1;
		  }
		}
.baseForm {
	
	// #ifdef H5
	min-height: calc(100vh - 44px);
	// #endif
	
	// #ifdef APP-PLUS
	min-height: calc(100vh - 44px);
	// #endif
	background-color: #F7F8FF;
	.tab-bar {
		padding: 0 40px;
	}
	.activeHeight {
		height: calc(100% - 44px);
	}
}

.list {
	.card {
		margin: $uni-page-padding;
		margin-top: 5px;
		margin-bottom: 5px;
		border-radius: 7px;
		display: flex;
		align-items: center;
		padding: 12px 10px 0px 10px;
		transition: all 300ms ease;
		box-shadow: 0 1px 5px rgba(19,11,236,0.13);
		background-color: #fff;
		display: flex;
		align-items: flex-start;
		.left {
			width: 155px;
			flex: 1;
		}
		.title {
			font-size: 14px;
			line-height: 40px;
			height: 40px;
			margin-top: 8px;
			font-weight: 600;
			color: #101010;
			border-top: 1px solid #E5EBFF;
		}
		.uni-btn {
			float: right;
			font-size: 12px;
			height: 24px;
			line-height: 24px;
			padding: 0 15px;
			margin-top: 7px;
			font-weight: 400;
		}
		.des {
			font-size: 12px;
			line-height: 20px;
			height: 20px;
			margin-bottom: 3px;
			white-space: nowrap;
			width: 140px;
		}
		.right {
			// flex: 1;
			flex-basis: calc(50% + 10px);
		}
	}
}
</style>
